package org.newlucene.core.index;

import java.io.IOException;

import org.newlucene.core.document.Document;
import org.newlucene.core.store.Directory;
import org.newlucene.core.store.OutputStream;

final class FieldDataWriter
{
	private FieldInfos fieldInfos;
	private OutputStream fieldsStream;
	private OutputStream indexStream;

	FieldDataWriter(Directory d, String segment, FieldInfos fn) throws IOException
	{
		fieldInfos = fn;
		fieldsStream = d.createFile(segment + ".fdt");
		indexStream = d.createFile(segment + ".fdx");
	}

	final void close() throws IOException
	{
		fieldsStream.close();
		indexStream.close();
	}

	final void addDocument(Document doc) throws IOException
	//count: stored field name in doc, 
	//field and its value in doc
	{
		indexStream.writeLong(fieldsStream.getFilePointer());

		// write the num of stored fields
		int storedCount = 0;
		for (FieldInfo fi : fieldInfos.getFieldInfoList())
		{
			if (doc.containsField(fi.name) && fi.isStore())
			{
				storedCount++;
			}
		}      
		fieldsStream.writeVInt(storedCount);
      
		// write the stored field values themselves
		for (FieldInfo fi : fieldInfos.getFieldInfoList())
		{
			if (doc.containsField(fi.name) && fi.isStore())
			{
				fieldsStream.writeVInt(fi.number);
				fieldsStream.writeString(doc.get(fi.name));
			}
		}      
	}
}